<template>
  <!-- 购物车页面 -->
  <div>
    <van-nav-bar fixed title="购物车" :right-text="rightText" left-arrow @click-right="changeCarState" @click-left="$utils.back($route.path)" />
    <div class="has-top has-bottom">
      <div>
        <!-- 结算列表 -->
        <div v-for="(item,index) in carList" v-show="buyState" :key="index" class="mt-30 mlr-25">
          <p class="checkbox fs-30" :class="item.check?'checked':''" @click="checkAll(index)">{{ item.PurchaseMemberName }}</p>
          <div v-for="(ite,inde) in item.PurchaseProductList" :key="inde" class="bg-white br-12 plr-20 mt-12">
            <div class="pt-20 flex-s-c">
              <img-box class="is-120 br-4 flex-s-0 flex-g-0" :img-url="ite.ProductImg" />
              <p class="text-show-line-2 pl-20 flex-1">{{ ite.ProductName }}</p>
            </div>
            <div v-for="(it,ind) in ite.CarSkuList" :key="ind" class="flex-s-c spec-item">
              <p class="checkbox  left-checkbox" :class="it.check?'checked':''" @click="check(ind,inde,index)" />
              <div class="flex-1 pl-20 pt-25 pb-30">
                <p v-show="it.Attribute" class=""><span class="color-gray-light">规格：</span>{{ it.DispalyAttribute }}</p>
                <div class="flex-s-c ">
                  <p class="color-primary ">￥<span class="fs-32">{{ it.Price }}</span> </p>
                  <div class=" flex-fe-c">
                    <span class="btn-minus flex-s-0 " :class="it.Amount<=0?'color-shadow':''" @click="changeAmount(it,it.Amount,it.Stock,-1,ite.MinNum,1,ite.LimitBuy,ite.AddNum,ind,inde,index)">-</span>
                    <div class="btn-input-box">
                      <input v-model="it.Amount" type="number" class="btn-input" @blur="changeAmount(it,it.Amount,it.Stock,0,ite.MinNum,1,ite.LimitBuy,ite.AddNum,ind,inde,index)">
                    </div>
                    <span class="btn-plus flex-s-0" :class="(it.Amount>=it.Stock||(it.Amount>=ite.LimitBuy&&ite.LimitBuy>0))?'color-shadow':''" @click="changeAmount(it,it.Amount,it.Stock,1,ite.MinNum,1,ite.LimitBuy,ite.AddNum,ind,inde,index)">+</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 编辑列表 -->
        <div v-for="(item,index) in carEditList" v-show="!buyState" :key="index+'m'" class="mt-30 mlr-25">
          <p class="checkbox fs-30" :class="item.check?'checked':''" @click="checkAEdit(index)">{{ item.PurchaseMemberName }}</p>
          <div v-for="(ite,inde) in item.PurchaseProductList" :key="inde+'m'" class="bg-white br-12 plr-20 mt-12">
            <div class="pt-20 flex-s-c">
              <img-box class="is-120 br-4 flex-s-0 flex-g-0" :img-url="ite.ProductImg" />
              <p class="text-show-line-2 pl-20 flex-1">{{ ite.ProductName }}</p>
            </div>
            <div v-for="(it,ind) in ite.CarSkuList" :key="ind+'m'" class="flex-s-c spec-item" @click="checkEdit(ind,inde,index)">
              <p class="checkbox  left-checkbox" :class="it.check?'checked':''" />
              <div class="flex-1 pl-20 pt-25 pb-30">
                <p v-show="it.Attribute" class=""><span class="color-gray-light">规格：</span>{{ it.DispalyAttribute }}</p>
                <div class="flex-s-c ">
                  <p class="color-primary ">￥<span class="fs-32">{{ it.Price }}</span> </p>
                </div>
              </div>
            </div>

          </div>

        </div>

        <!-- 购物车为空时显示内容 -->
        <div v-show="!carList || carList.length===0" class="mt-140 tac">
          <img class="cart-empty" src="@/assets/images/cart-empty.png" alt="空的购物车">
          <p class="mt-20 fs-28">您的购物车空空如也~</p>
          <p class="color-gray-light">再忙，也要记得买点什么犒劳自己哦</p>
          <span class="btn-small bg-primary mt-30" @click="gotoproduct">去逛逛</span>
        </div>

      </div>
    </div>
    <!-- 底部栏购物车 -->
    <shopCart
      :car-list="carList"
      :buy-state="buyState"
      :total-num="totalAmount"
      :total-price="totalPrice"
      :check-all-state="checkAllState"
      car-type="shopCar"
      @goSubmitOrder="goSubmitOrder"
      @checkAll="checkAllEdit"
      @cleanCart="cleanCart"
      @DeleteUserCar="DeleteUserCar"
    />

  </div>
</template>

<script>
import imgBox from 'components/imgBox'
import shopCart from 'components/purchase/shopCart'
import { GetPurchaseCarListPage, AddPurchaseCars, DeletePurchaseCars } from 'api/purchase'
export default {
  components: { imgBox, shopCart },
  data() {
    return {
      rightText: '编辑',
      buyState: true,
      // 编辑相关数据
      carEditList: [],
      editIds: '',
      checkAllState: false,

      // 结算相关数据
      ids: '',
      carList: [],
      totalAmount: 0,
      totalPrice: 0,
      checkPurchaseMemberId: 0
    }
  },
  computed: {},
  created() {
    this.GetPurchaseCarListPage()
  },

  methods: {
    gotoproduct() {
      this.$router.push('/purchase/order')
    },
    cleanData() {
      this.carEditList = []
      this.carList = []
      this.editIds = ''
      this.ids = ''
      this.checkAllState = false
      this.totalAmount = 0
      this.totalPrice = 0
      this.checkPurchaseMemberId = 0
    },
    changeCarState() {
      this.buyState = !this.buyState
      this.rightText = this.buyState ? '编辑' : '完成'
    },
    changeAmount(item, num, stock, type, min, unitRatio, limit, addNum, ind, inde, index) {
      console.log(ind)
      const _this = this
      const _oldAmount = item.Amount
      this.$utils.changeAmount(item, num, stock, type, min, unitRatio, limit, addNum)
      if (_oldAmount !== item.Amount || type === 0) {
        const _list = []
        _list.push(item)
        const _obj = {
          carList: _list,
          puchaseMemberId: item.PurchaseMemberId
        }
        console.log(_obj)
        if (item.check) {
          _this.totalAmount += Number(item.Amount) - Number(_oldAmount)
          _this.totalPrice += (Number(item.Amount) - Number(_oldAmount)) * Number(item.Price)
        }
        if (item.Amount === 0) {
          _this.ids = _this.ids.replace((item.Id + ','), '')
          _this.deleteItem(index, inde, ind)
        }
        this.AddPurchaseCars(_obj)
      }
    },
    // 列表删除项
    deleteItem(index, inde, ind) {
      const _this = this
      _this.carList[index].PurchaseProductList[inde].CarSkuList.splice(ind, 1)
      _this.carEditList[index].PurchaseProductList[inde].CarSkuList.splice(ind, 1)
      if (_this.carList[index].PurchaseProductList[inde].CarSkuList.length === 0) {
        _this.carList[index].PurchaseProductList.splice(inde, 1)
        _this.carEditList[index].PurchaseProductList.splice(inde, 1)
        if (_this.carList[index].PurchaseProductList.length === 0) {
          _this.carList.splice(index, 1)
          _this.carEditList.splice(index, 1)
        }
      }
      _this.carList[index].check = _this.isShoepCheckAll(index)
      _this.carEditList[index].check = _this.isEditShoepCheckAll(index)
      _this.checkAllState = _this.isCheckAll()
    },
    // 全选/全不选(结算)
    checkAll(index) {
      const _this = this
      const _checkALL = _this.carList[index].check
      const _purchaseMemberId = _this.carList[index].PurchaseMemberId
      if (_checkALL) {
        // 取消全选操作
        _this.checkPurchaseMemberId = 0
        _this.ids = ''
        _this.totalPrice = 0
        _this.totalAmount = 0
        _this.carList[index].check = false
        if (_this.carList[index].PurchaseProductList && _this.carList[index].PurchaseProductList.length > 0) {
          _this.carList[index].PurchaseProductList.forEach(ite => {
            if (ite.CarSkuList && ite.CarSkuList.length > 0) {
              ite.CarSkuList.forEach(it => {
                it.check = false
              })
            }
          })
        }
      } else if (_this.checkPurchaseMemberId !== 0 && _this.checkPurchaseMemberId !== _purchaseMemberId) {
        _this.$toast('不能同时选中两家供应商的商品')
      } else {
        // 全选操作
        _this.checkPurchaseMemberId = _purchaseMemberId
        _this.carList[index].check = true
        _this.ids = ''
        _this.totalPrice = 0
        _this.totalAmount = 0
        if (_this.carList[index].PurchaseProductList && _this.carList[index].PurchaseProductList.length > 0) {
          _this.carList[index].PurchaseProductList.forEach(ite => {
            if (ite.CarSkuList && ite.CarSkuList.length > 0) {
              ite.CarSkuList.forEach(it => {
                it.check = true
                _this.ids += it.Id + ','
                _this.totalAmount += Number(it.Amount)
                _this.totalPrice += Number(it.Amount) * Number(it.Price)
              })
            }
          })
        }
      }
    },
    // 选择/不选（结算）
    check(ind, inde, index) {
      const _this = this
      const _check = _this.carList[index].PurchaseProductList[inde].CarSkuList[ind].check
      const _it = _this.carList[index].PurchaseProductList[inde].CarSkuList[ind]
      const _purchaseMemberId = _this.carList[index].PurchaseMemberId
      if (_check) {
        // 取消选择
        _this.carList[index].PurchaseProductList[inde].CarSkuList[ind].check = false
        _this.carList[index].check = false
        _this.ids = _this.ids.replace((_it.Id + ','), '')
        _this.totalAmount -= Number(_it.Amount)
        _this.totalPrice -= Number(_it.Amount) * Number(_it.Price)
        if (_this.ids === '') {
          _this.checkPurchaseMemberId = 0
        }
      } else if (_this.checkPurchaseMemberId !== 0 && _this.checkPurchaseMemberId !== _purchaseMemberId) {
        _this.$toast('不能同时选中两家供应商的商品')
      } else {
        // 选择操作
        _this.carList[index].PurchaseProductList[inde].CarSkuList[ind].check = true
        _this.ids += _it.Id + ','
        _this.totalAmount += Number(_it.Amount)
        _this.totalPrice += Number(_it.Amount) * Number(_it.Price)
        _this.checkPurchaseMemberId = _purchaseMemberId
        _this.carList[index].check = _this.isShoepCheckAll(index)
      }
    },
    // 去结算
    goSubmitOrder() {
      if (this.ids) {
        this.$router.push('/purchase/productsubmitorder/' + this.ids)
      } else {
        this.$toast('请至少选择一样商品')
      }
    },

    // 商户全选、全不选（编辑）
    checkAEdit(index) {
      const _this = this
      const _checkALL = _this.carEditList[index].check
      if (_checkALL) {
        // 取消全选操作
        _this.editIds = ''
        _this.carEditList[index].check = false
        if (_this.carEditList[index].PurchaseProductList && _this.carEditList[index].PurchaseProductList.length > 0) {
          _this.carEditList[index].PurchaseProductList.forEach(ite => {
            if (ite.CarSkuList && ite.CarSkuList.length > 0) {
              ite.CarSkuList.forEach(it => {
                it.check = false
              })
            }
          })
        }
      } else {
        // 全选操作
        _this.carEditList[index].check = true
        _this.editIds = ''
        if (_this.carEditList[index].PurchaseProductList && _this.carEditList[index].PurchaseProductList.length > 0) {
          _this.carEditList[index].PurchaseProductList.forEach(ite => {
            if (ite.CarSkuList && ite.CarSkuList.length > 0) {
              ite.CarSkuList.forEach(it => {
                it.check = true
                _this.editIds += it.Id + ','
              })
            }
          })
        }
      }
      _this.checkAllState = _this.isCheckAll()
      _this.$forceUpdate()
    },
    // 选择/不选（编辑）
    checkEdit(ind, inde, index) {
      const _this = this
      const _check = _this.carEditList[index].PurchaseProductList[inde].CarSkuList[ind].check
      const _it = _this.carEditList[index].PurchaseProductList[inde].CarSkuList[ind]
      if (_check) {
        // 取消选择
        _this.carEditList[index].PurchaseProductList[inde].CarSkuList[ind].check = false
        _this.carEditList[index].check = false
        _this.editIds = _this.editIds.replace((_it.Id + ','), '')
      } else {
        // 选择操作
        _this.carEditList[index].PurchaseProductList[inde].CarSkuList[ind].check = true
        _this.editIds += _it.Id + ','
        let _checkAll = true
        _this.carEditList[index].PurchaseProductList.forEach(ite => {
          if (ite.CarSkuList && ite.CarSkuList.length > 0) {
            ite.CarSkuList.forEach(it => {
              if (!it.check || it.check === false) {
                _checkAll = false
              }
            })
          }
        })
        if (_checkAll) {
          _this.carEditList[index].check = true
        }
      }
      _this.checkAllState = _this.isCheckAll()
      _this.$forceUpdate()
    },

    // 判断商户是否全选（结算）
    isShoepCheckAll(index) {
      let _checkAll = true
      this.carList[index].PurchaseProductList.forEach(ite => {
        if (ite.CarSkuList && ite.CarSkuList.length > 0) {
          ite.CarSkuList.forEach(it => {
            if (!it.check || it.check === false) {
              _checkAll = false
            }
          })
        }
      })
      return _checkAll
    },

    // 判断商户是否全选（结算）
    isEditShoepCheckAll(index) {
      let _checkAll = true
      this.carEditList[index].PurchaseProductList.forEach(ite => {
        if (ite.CarSkuList && ite.CarSkuList.length > 0) {
          ite.CarSkuList.forEach(it => {
            if (!it.check || it.check === false) {
              _checkAll = false
            }
          })
        }
      })
      return _checkAll
    },

    // 判断是否全选
    isCheckAll() {
      let isCheckAll = true
      if (this.carEditList && this.carEditList.length > 0) {
        this.carEditList.forEach(item => {
          if (!item.check || item.check === false) {
            isCheckAll = false
          }
        })
      }
      return isCheckAll
    },

    // 设置全选、全不选（编辑）
    setEditCheck(bol) {
      const _this = this
      _this.editIds = ''
      if (_this.carEditList && _this.carEditList.length > 0) {
        _this.carEditList.forEach(item => {
          item.check = bol
          if (item.PurchaseProductList && item.PurchaseProductList.length > 0) {
            item.PurchaseProductList.forEach(ite => {
              if (ite.CarSkuList && ite.CarSkuList.length > 0) {
                ite.CarSkuList.forEach(it => {
                  it.check = bol
                  if (bol) {
                    _this.editIds += (it.Id + ',')
                  }
                })
              }
            })
          }
        })
      }
    },

    // 全选/全不选(编辑)
    checkAllEdit() {
      this.checkAllState = !this.checkAllState
      this.setEditCheck(this.checkAllState)
      this.$forceUpdate()
    },
    // 清空购物车
    cleanCart() {
      if (!this.carEditList || this.carEditList.length === 0) {
        this.$toast.fail('购物车中无商品')
        return
      }
      this.checkAllState = true
      this.setEditCheck(true)
      this.DeletePurchaseCars(this.editIds, true)
    },
    // 删除购物车商品
    DeleteUserCar() {
      if (!this.editIds) {
        this.$toast.fail('未选中商品')
        return
      }
      this.DeletePurchaseCars(this.editIds)
    },
    // 本地列表同步删除掉的商品
    // updateList() {
    //   this.updatSubmit()
    // },
    // 同步结算信息
    updateList() {
      const _this = this
      if (_this.carList && _this.carList.length > 0) {
        for (let i = 0; i < _this.carList.length; i++) {
          if (_this.carList[i].PurchaseProductList && this.carList[i].PurchaseProductList.length > 0) {
            for (let j = 0; j < _this.carList[i].PurchaseProductList.length; j++) {
              if (_this.carList[i].PurchaseProductList[j].CarSkuList && this.carList[i].PurchaseProductList[j].CarSkuList.length > 0) {
                for (let k = 0; k < _this.carList[i].PurchaseProductList[j].CarSkuList.length; k++) {
                  const it = _this.carList[i].PurchaseProductList[j].CarSkuList[k]
                  if (_this.ids.indexOf(it.Id) >= 0 && _this.editIds.indexOf(it.Id) >= 0) {
                    _this.ids = _this.ids.replace((it.Id + ','), '')
                    _this.totalAmount -= Number(it.Amount)
                    _this.totalPrice -= Number(it.Amount) * Number(it.Price)
                  }
                  if (_this.editIds.indexOf(it.Id) >= 0) {
                    _this.carList[i].PurchaseProductList[j].CarSkuList.splice(k, 1)
                    _this.carEditList[i].PurchaseProductList[j].CarSkuList.splice(k, 1)
                    k--
                  }
                }
              }
            }
          }
        }
      }
      _this.editIds = ''
      if (_this.carList && _this.carList.length > 0) {
        for (let i = 0; i < _this.carList.length; i++) {
          if (_this.carList[i].PurchaseProductList && this.carList[i].PurchaseProductList.length > 0) {
            for (let j = 0; j < _this.carList[i].PurchaseProductList.length; j++) {
              if (_this.carList[i].PurchaseProductList[j].CarSkuList && this.carList[i].PurchaseProductList[j].CarSkuList.length === 0) {
                _this.carList[i].PurchaseProductList.splice(j, 1)
                _this.carEditList[i].PurchaseProductList.splice(j, 1)
                j--
              }
            }
          }
          _this.carList[i].check = _this.isShoepCheckAll(i)
          _this.carEditList[i].check = _this.isEditShoepCheckAll(i)
        }
      }
      if (_this.carList && _this.carList.length > 0) {
        for (let i = 0; i < _this.carList.length; i++) {
          if (_this.carList[i].PurchaseProductList && this.carList[i].PurchaseProductList.length === 0) {
            _this.carList.splice(i, 1)
            _this.carEditList.splice(i, 1)
            i--
          }
        }
      }
      _this.checkAllState = _this.isCheckAll()
    },
    // 同步列表
    deleteList(arr, tag) {

    },

    // 获取购物车数据
    GetPurchaseCarListPage() {
      const _this = this
      GetPurchaseCarListPage().then(res => {
        if (res) {
          _this.carList = JSON.parse(JSON.stringify(res.Data))
          _this.carEditList = JSON.parse(JSON.stringify(res.Data))

          if (_this.carList && _this.carList.length > 0) {
            _this.carList.forEach((item, index) => {
              item.check = index === 0
              if (index === 0) {
                _this.checkPurchaseMemberId = item.PurchaseMemberId
              }
              if (item.PurchaseProductList && item.PurchaseProductList.length > 0) {
                item.PurchaseProductList.forEach(ite => {
                  if (ite.CarSkuList && ite.CarSkuList.length > 0) {
                    ite.CarSkuList.forEach(it => {
                      it.PurchaseMemberId = item.PurchaseMemberId
                      it.check = index === 0
                      if (index === 0) {
                        _this.ids += it.Id + ','
                        _this.totalAmount += Number(it.Amount)
                        _this.totalPrice += Number(it.Amount) * Number(it.Price)
                      }
                    })
                  }
                })
              }
            })
          }
          if (_this.carEditList && _this.carEditList.length > 0) {
            _this.carEditList.forEach((item, index) => {
              item.check = false
              if (item.PurchaseProductList && item.PurchaseProductList.length > 0) {
                item.PurchaseProductList.forEach(ite => {
                  if (ite.CarSkuList && ite.CarSkuList.length > 0) {
                    ite.CarSkuList.forEach(it => {
                      it.check = false
                    })
                  }
                })
              }
            })
          }
        }
      })
    },

    // 添加购物车
    AddPurchaseCars(obj) {
      AddPurchaseCars(obj).then(res => {
        if (res) {
          console.log('成功')
        }
      })
    },
    // 删除购物车数据
    DeletePurchaseCars(ids, bol = false) {
      ids = ids.substr(0, ids.length - 1)
      DeletePurchaseCars({ ids }).then(res => {
        if (res) {
          this.$toast.success('删除成功')
          if (bol) {
            this.cleanData()
          } else {
            this.updateList()
          }
        }
      })
    }
  }

}
</script>
<style lang="scss" scoped>
.checkbox{
 padding-left: 75px;
 &:before{
   top: 3px;
   left: 23px;
 }
 &:after{
   top: 6px;
   left: 35px;
 }
}
.left-checkbox{
  width: 120px;
  height: 32px;
   &:before{
     top: 0;
   left: 44px;
 }
 &:after{
   left: 56px;
   top: 4px;
 }
}
.spec-item{
  border-bottom: 1px dashed $colorBorder;
  &:last-child{
    border-bottom: none;
  }
}
/deep/.van-nav-bar__right {
  .van-nav-bar__text {
    color:$color3 ;
  }
}
.cart-empty{
  width: 170px;
  height: 110px;
}
.btn-small{
  line-height: 74px;
  font-size: 28px;
  padding: 0 60px;
  border-radius: 37px;
}
</style>
